package spring.cloud.tasks.tasks_manager.service;

import com.alibaba.fastjson2.JSON;
import spring.cloud.tasks.common.curator.Curator;

import java.util.List;
import java.util.concurrent.CountDownLatch;

class SaveOnlineExecutorToZooKeeperThread extends Thread {
    private final Curator curator;
    private final List<OnlineExecutorTaskItemPartitionNodeAndData> onlineExecutorTaskItemPartitionNodeAndDataList;
    private final CountDownLatch countDownLatch;

    public SaveOnlineExecutorToZooKeeperThread(Curator curator, List<OnlineExecutorTaskItemPartitionNodeAndData> onlineExecutorTaskItemPartitionNodeAndDataList, CountDownLatch countDownLatch) {
        this.curator = curator;
        this.onlineExecutorTaskItemPartitionNodeAndDataList = onlineExecutorTaskItemPartitionNodeAndDataList;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        try {
            for (OnlineExecutorTaskItemPartitionNodeAndData onlineExecutorTaskItemPartitionNodeAndData :
                    onlineExecutorTaskItemPartitionNodeAndDataList) {
                try {
                    curator.create(onlineExecutorTaskItemPartitionNodeAndData.getPath(), JSON.toJSONString(onlineExecutorTaskItemPartitionNodeAndData));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } finally {
            countDownLatch.countDown();
        }
    }
}
